package com.atguigu.datastream.test.day03;

import com.atguigu.datastream.bean.Event;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * ClassName: Flink_Source_Kafka
 * Package: com.atguigu.day03
 * Description:
 *                   reduce
 * @Author ChenJun
 * @Create 2023/4/8 16:40
 * @Version 1.0
 */
public class Flink_11_Transformat_Reduce {
    public static void main(String[] args) throws Exception {
        //1.获取Flink 流的运行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        // 2 . 从端口读取数据
        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);


        //TODO 将读进来的字符串转为Event
        SingleOutputStreamOperator<Event> map = streamSource.map(new MapFunction<String, Event>() {
            @Override
            public Event map(String s) throws Exception {
                String[] split = s.split(",");

                return new Event(split[0], split[1], Long.parseLong(split[2]));
            }
        });


        KeyedStream<Event, String> keyBy = map.keyBy(new KeySelector<Event, String>() {
            @Override
            public String getKey(Event event) throws Exception {
                return event.user;
            }
        });

        // TODO 求最大的时间戳 每个分组的第一条数据不进reduce方法
        keyBy.reduce(new ReduceFunction<Event>() {

            /**
             *
             * @param t1   上一次聚合的结果
             * @param t2   当前的数据
             * @return
             * @throws Exception
             */
            @Override
            public Event reduce(Event t1, Event t2) throws Exception {
                System.out.println("________reduce__________");
                return new Event(t1.user,t1.url,Math.max(t1.timestamp, t2.timestamp));
            }
        }).print();

        env.execute();
    }
}
